package com.qsmx.store.app.util;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.qsmx.store.app.fusion.FusionCode;
import com.qsmx.store.core.net.HttpUrl;

import java.io.File;
import java.util.UUID;

/**
 * 文 件 名:
 * 描    述:  通用Util
 * 创 建 人:  Xian
 * 创建时间:  2016/5/19 0019 下午 4:18
 */
public class CommonUtils {
    //点分隔
    private static final String DOT = ".";


    /**
     * 生成缓存文件名称
     *
     * @param type 文件类型
     * @return
     */
    public static String generateFileName(FusionCode.FileType type) {

        String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();

        switch (type) {
            case FILE_TYPE_IMAGE:     //图片
                fileName = fileName.concat(DOT).concat(FusionCode.SUFFIX_IMAGE_FILE);
                break;
            case FILE_TYPE_AUDIO:     //音频
                fileName = fileName.concat(DOT).concat(FusionCode.SUFFIX_AUDIO_FILE);
                break;
            case FILE_TYPE_VIDEO:     //视频
                fileName = fileName.concat(DOT).concat(FusionCode.SUFFIX_VIDEO_FILE);
                break;
            case FILE_TYPE_TMP:       //临时文件
                fileName = fileName.concat(DOT).concat(FusionCode.SUFFIX_TMP_FILE);
                break;
            case FILE_TYPE_THUMBNAIL://缩略图
                fileName = fileName.concat(DOT).concat(FusionCode.SUFFIX_IMAGE_THUMBNAIL);
                break;
        }

        return fileName;

    }

    /**
     * @return
     * @Description 判断存储卡是否存在
     */
    public static boolean checkSDCard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }

        return false;
    }

    public static OSS makeOSSService(Context mContext) {
//        OSSService ossService = OSSServiceProvider.getService();
//        ossService.setApplicationContext(MyApplication.instance);
//        final String accessKey = FusionField.OSS_ACCESS_KEY;
//        final String secretKey = FusionField.OSS_SECRET_KEY;
//        ossService.setGlobalDefaultTokenGenerator(new TokenGenerator() {
//            @Override
//            public String generateToken(String httpMethod, String md5, String type, String date, String ossHeaders,
//                                        String resource) {
//
//                String content = httpMethod + "\n" + md5 + "\n" + type + "\n" + date
//                        + "\n" + ossHeaders + resource;
//
//                return OSSToolKit.generateToken(accessKey, secretKey, content);
//            }
//        });
//        ossService.setGlobalDefaultACL(AccessControlList.PUBLIC_READ);
//        ossService.setGlobalDefaultHostId(FusionCode.API_OSS_HOST_ADDRESS);
//        ossService.setApplicationContext(MyApplication.instance);
//        ClientConfiguration conf = new ClientConfiguration();
//        ossService.setClientConfiguration(conf);

// 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的访问控制章节
        String stsServer = HttpUrl.STS_SYSTEM;
        OSSAuthCredentialsProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(mContext, "http://oss-cn-hangzhou.aliyuncs.com", credentialProvider, conf);

        return oss;
    }

    /**
     * 获取临时文件
     *
     * @param fileName 临时文件文件名
     * @return
     */
    public static File getAppTmpFile(String fileName, Context mContext) throws Exception {

        if (!checkSDCard()) {
            Log.e("CommonUtils", "SD card did not mounted");
            throw new Exception("SD card did not mounted");
        }

        File tmpFile = new File(mContext.getExternalFilesDir("").getAbsolutePath() + "/qgy/cache/video/");

        if (!tmpFile.exists()) {

            boolean result = tmpFile.mkdirs();

            if (result) {
                return new File(tmpFile, fileName);
            }

            return null;
        }

        return new File(tmpFile, fileName);
    }

    //判断该类是不是顶部类
    public static boolean isTopActivy(Context context, String activityName) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cName = am.getRunningTasks(1).size() > 0 ? am
                .getRunningTasks(1).get(0).topActivity : null;

        if (null == cName)
            return false;
        return cName.getClassName().equals(activityName);
    }

    //获取顶部Activity
    public static String getTopActivy(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cName = am.getRunningTasks(1).size() > 0 ? am
                .getRunningTasks(1).get(0).topActivity : null;

        return cName.getClassName();
    }
}
